package com.jnu.myfirstapplication;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.jnu.myfirstapplication.data.Book;
import com.jnu.myfirstapplication.data.DataSaver;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import java.util.UUID;

public class InputBookItemActivity extends AppCompatActivity {

    public static final int RESULT_CODE_SUCCESS = 666;
    private int position;
    Random random = new Random();
    int index = random.nextInt(11);
    int id=-1;
    int BookShelf;
    String title;
    String Author;
    String Translator;
    String Publisher;
    String PubDate;
    String ISBN;
    int ReadingState;
//    com.jnu.myfirstapplication.data.BookShelf = this.getIntent().getIntExtra("BookShelf", 0);
    String Notes;
    String Label;
    String Website;
    Book book;
    String uuid;
    boolean flag=true;  //判断是否是新书而不是编辑





    int[] mArray = {
            R.drawable.book_1,
            R.drawable.book_2,
            R.drawable.book_no_name,
            R.drawable.jidushan,
            R.drawable.brother,
            R.drawable.live,
            R.drawable.ming,
            R.drawable.summer,
            R.drawable.tired,
            R.drawable.war,
            R.drawable.western
    };

//    public class MyAdapter extends BaseAdapter {
//
//        private ArrayList<String> bookArrayList;
//        private Context mContext;
//
//        public MyAdapter(Context mContext, ArrayList<String> list){
//            this.mContext = mContext;
//            bookArrayList = list;
//        }
//
//        @Override
//        public View getView(int position, View convertView, ViewGroup parent) {
//            LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//            View view = layoutInflater.inflate(R.layout.spinner_view, parent, false);
//            TextView textView = view.findViewById(R.id.bookShelfItem);
//            textView.setText(bookArrayList.get(position));
//            return view;
//        }
//
//        @Override
//        public int getCount() {
//            return bookArrayList == null ? 0 : bookArrayList.size();
//        }
//
//        @Override
//        public String getItem(int position) {
//            return bookArrayList.get(position);
//        }
//
//        @Override
//        public long getItemId(int position) {
//            return position;
//        }
//
//    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_input_book_item);
        setTitle("Add or edit Book");
        Toast.makeText(getApplicationContext(),"必须输入标题！",Toast.LENGTH_SHORT);
//        String title = this.getIntent().getStringExtra("title");
////        Double price=this.getIntent().getDoubleExtra("price",0);
////        int id=this.getIntent().getIntExtra("id",700010);
//        String Author = this.getIntent().getStringExtra("Author");
//        String Translator = this.getIntent().getStringExtra("Translator");
//        String Publisher = this.getIntent().getStringExtra("Publisher");
//        String PubDate = this.getIntent().getStringExtra("PubDate");
//        String ISBN = this.getIntent().getStringExtra("ISBN");
//        int ReadingState = this.getIntent().getIntExtra("ReadingState", 0);
//        BookShelf = this.getIntent().getIntExtra("BookShelf", 0);
//        id = this.getIntent().getIntExtra("id", -1);
//        String Notes = this.getIntent().getStringExtra("Notes");
//        String Label = this.getIntent().getStringExtra("Label");
//        String Website = this.getIntent().getStringExtra("Website");

        title = this.getIntent().getStringExtra("title");
        Author = this.getIntent().getStringExtra("Author");
        Translator = this.getIntent().getStringExtra("Translator");
        Publisher = this.getIntent().getStringExtra("Publisher");
        PubDate = this.getIntent().getStringExtra("PubDate");
        ISBN = this.getIntent().getStringExtra("ISBN");
        ReadingState = this.getIntent().getIntExtra("ReadingState", 0);
        BookShelf = this.getIntent().getIntExtra("BookShelf", 0);
        id = this.getIntent().getIntExtra("id", -1);
        Notes = this.getIntent().getStringExtra("Notes");
        Label = this.getIntent().getStringExtra("Label");
        Website = this.getIntent().getStringExtra("Website");




        Spinner spinner = findViewById(R.id.edittext_book_item_BookShelf);
//        ImageView editIntid=findViewById(R.id.image_view_book_cover);
        EditText editTextTitle = findViewById(R.id.edittext_book_item_title);
//        EditText editTextPrice=findViewById(R.id.edittext_book_item_price);
        EditText editTextAuthor = findViewById(R.id.edittext_book_item_Author);
        EditText editTextTranslator = findViewById(R.id.edittext_book_item_Translator);
        EditText editTextPublisher = findViewById(R.id.edittext_book_item_Publisher);
        EditText editTextPubDate = findViewById(R.id.edittext_book_item_PubDate);
        EditText editTextISBN = findViewById(R.id.edittext_book_item_ISBN);
        Spinner editTextReadingState = findViewById(R.id.edittext_book_item_ReadingState);

        Spinner editTextBookShelf = findViewById(R.id.edittext_book_item_BookShelf);
        EditText editTextNotes = findViewById(R.id.edittext_book_item_Notes);
        TextView editTextLabel = findViewById(R.id.edittext_book_item_Label);
        EditText editTextWebsite = findViewById(R.id.edittext_book_item_Website);

        ImageView cover = findViewById(R.id.book_image);



        editTextLabel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                AlertDialog.Builder builder = new AlertDialog.Builder(InputBookItemActivity.this);
                builder.setTitle("请选择要贴上的标签：");

                String [] labels=BookListMainActivity.labels.toArray(new String[BookListMainActivity.labels.size()]);

                boolean[] checkedItems=new boolean[BookListMainActivity.labels.size()];

                ArrayList<String> itemLabel=new ArrayList<>();
                if(flag==false){
                    BookListMainActivity.eachBookHash.get(uuid).forEach((key, value) -> {
                        itemLabel.add(key);
                    });
                }else{
                    BookListMainActivity.eachBookHash.put(uuid,new HashMap<>());
                }

                String [] tran=itemLabel.toArray(new String[1]);
                System.out.println(tran);

                for(int i=0;i<BookListMainActivity.labels.size();i++){
                    if(itemLabel.contains(BookListMainActivity.labels.get(i))){
                        checkedItems[i]=true;
                    }else
                    {
                        checkedItems[i]=false;
                    }
                }

                ArrayList<String> decidedLabel = new ArrayList<>();
                ArrayList<String> cancelLabel = new ArrayList<>();
                builder.setMultiChoiceItems(labels, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                        if (isChecked) {
                            decidedLabel.add(labels[which]);
                            cancelLabel.remove(labels[which]);
                        } else {
                            decidedLabel.remove(labels[which]);
                            cancelLabel.add(labels[which]);
                        }
                    }
                });

                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        System.out.println(decidedLabel);

                        //以下把新增的弄完了
                        for(String string:decidedLabel){
                            if(!string.equals("default")) {
                                int[] temp = {0,BookListMainActivity.hashMaps.get(string).get("default").size()};
                                if(title!=null){
                                    Book book =new Book(title,id,Author,Translator,Publisher,PubDate,ISBN,ReadingState,0,
                                            Notes,Label,Website,BookListMainActivity.hashMaps.get(string).get("default").size());
                                    book.setUuid(uuid);
                                    System.out.println(BookListMainActivity.hashMaps);
                                    BookListMainActivity.eachBookHash.get(uuid).put(string,temp);
                                    BookListMainActivity.hashMaps.get(string).get("default").add(book);
                                }else{
                                    Toast.makeText(InputBookItemActivity.this,"必须输入标题！",Toast.LENGTH_SHORT);
                                }
                            }
                        }
                        //接下来弄取消掉的标签
                        for(String string:cancelLabel){
                            if(!string.equals("default")) {
                                int bs= BookListMainActivity.eachBookHash.get(uuid).get(string)[0];
                                int ps= BookListMainActivity.eachBookHash.get(uuid).get(string)[1];
                                BookListMainActivity.hashMaps.get(string).get(BookListMainActivity.bookShelfStringArray.get(bs)).remove(ps);
                                BookListMainActivity.eachBookHash.get(uuid).remove(string);
                            }
                        }

                        System.out.println(BookListMainActivity.eachBookHash);
//                        Toast.makeText(InputBookItemActivity.this, "你选择了: " + result, Toast.LENGTH_SHORT).show();

                        new DataSaver().saveHashMaps(InputBookItemActivity.this,BookListMainActivity.hashMaps);
                        new DataSaver().saveEachBook(InputBookItemActivity.this,BookListMainActivity.eachBookHash);

                        dialog.dismiss();
                        finish();
                    }
                });

                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        decidedLabel.clear();
                        dialog.dismiss();
                    }
                });
                AlertDialog dialog = builder.create();      //创建AlertDialog对象
                dialog.show();                               //显示对话框
            }
        });




        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, BookListMainActivity.bookShelfStringArray);
        editTextBookShelf.setAdapter(adapter);


        Drawable drawable;

        if (id == -1) {
            drawable = getBaseContext().getResources().getDrawable(mArray[index]);
            id = index;
            uuid=UUID.randomUUID().toString();
            editTextLabel.setClickable(false);
            flag=true;
        } else {
            drawable=null;
            try{
                String path="/sdcard/Pictures/book/book"+id+".jpg";
                if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
//                    requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), REQUEST_CODE_CALL_PHONE);
                    ActivityCompat.requestPermissions(InputBookItemActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);
                }
                Bitmap bitmap  = BitmapFactory.decodeFile(path);
                drawable = new BitmapDrawable(getResources(), bitmap);
            }catch (Exception e){
                e.printStackTrace();
            }
//            drawable = getBaseContext().getResources().getDrawable(mArray[id]);
            if(drawable==null){
                drawable=getBaseContext().getResources().getDrawable(mArray[index]);
            }
            uuid=this.getIntent().getStringExtra("UUID");
            flag=false;
        }
        cover.setImageDrawable(drawable);

        if (null != title) {
            editTextTitle.setText(title);
            editTextAuthor.setText(Author);
            editTextTranslator.setText(Translator);
            editTextPublisher.setText(Publisher);
            editTextPubDate.setText(PubDate);
            editTextISBN.setText(ISBN);
            editTextReadingState.setSelection(ReadingState);
            editTextNotes.setText(Notes);
            editTextLabel.setText(Label);
            editTextWebsite.setText(Website);
        }
        editTextBookShelf.setSelection(BookShelf);  //书架单独设置，因为这个必定传过去了


//        if (book != null) {
//            editTextTitle.setText(title);
//            editTextAuthor.setText(Author);
//            editTextTranslator.setText(Translator);
//            editTextPublisher.setText(Publisher);
//            editTextPubDate.setText(PubDate);
//            editTextISBN.setText(ISBN);
//            editTextReadingState.setSelection(ReadingState);
//            editTextBookShelf.setSelection(BookShelf);
//            editTextNotes.setText(Notes);
//            editTextLabel.setText(Label);
//            editTextWebsite.setText(Website);
//        }

        position = this.getIntent().getIntExtra("position", 0);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                //
                String info = adapterView.getItemAtPosition(i).toString();//获取i所在的文本
                if (info.equals("Add New")) {
                    Toast.makeText(InputBookItemActivity.this, info, Toast.LENGTH_SHORT).show();
                    alert_edit();
                    adapterView.setSelection(BookShelf);
                }

//                Toast.makeText(InputBookItemActivity.this, info, Toast.LENGTH_SHORT).show();
//                alert_edit();
//                adapterView.setSelection(BookShelf);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

    }
    String name;
    public void alert_edit () {
        final EditText et = new EditText(this);
        new AlertDialog.Builder(this).setTitle("请输入消息")
                .setIcon(android.R.drawable.sym_def_app_icon)
                .setView(et)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //按下确定键后的事件
                        name=et.getText().toString();
                        //先假设没有这个书架并且书架里没有这本书，先new一个，等一下再做判断是否已经存在了这个书架，用hashmap把书架的name传进去
                        if(BookListMainActivity.bookBookShelfHashMap.containsKey(name)){
                            //查到了，说明用户重复输入了一个书架的名字，就直接加入已有的书架了
                            BookListMainActivity.bookBookShelfHashMap.get(name).add(new Book(title,id,Author,Translator,Publisher,PubDate,ISBN,ReadingState,BookShelf,Notes,Label,Website,
                                    BookListMainActivity.bookBookShelfHashMap.get(name).size()));
                            new DataSaver().save(InputBookItemActivity.this,BookListMainActivity.bookList,BookListMainActivity.bookShelfStringArray);

//                            Intent intent=new Intent();
//                            setResult(RESULT_CODE_SUCCESS,intent);

                            finish();
                        }else{//查找不到，说明确实是新书架而非用户重复输入一个书架的名字
                            BookListMainActivity.bookShelfStringArray.add(BookListMainActivity.bookShelfStringArray.size()-1,name); //在倒数第二个位置插入
                            ArrayList<Book> bookShelfList=new ArrayList<>();
                            BookListMainActivity.hashMaps.get(BookListMainActivity.label).put(name,new ArrayList<>());
                            setResult(201);
                            finish();
                        }
                        System.out.println(BookListMainActivity.bookBookShelfHashMap);
                        new DataSaver().save(InputBookItemActivity.this,BookListMainActivity.bookList,BookListMainActivity.bookShelfStringArray);
                        new DataSaver().saveHashMap(InputBookItemActivity.this,BookListMainActivity.bookBookShelfHashMap);
                        new DataSaver().saveHashMaps(InputBookItemActivity.this,BookListMainActivity.hashMaps);
//                        BookListMainActivity.bookshelf.put()
                        Toast.makeText(getApplicationContext(), et.getText().toString(), Toast.LENGTH_LONG).show();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //按下确定键后的事件
                        Toast.makeText(getApplicationContext(), et.getText().toString(), Toast.LENGTH_LONG).show();
                    }
                }).show();
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
//        ImageView editIntid=findViewById(R.id.image_view_book_cover);
        EditText editTextTitle=findViewById(R.id.edittext_book_item_title);
//        EditText editTextPrice=findViewById(R.id.edittext_book_item_price);
        EditText editTextAuthor=findViewById(R.id.edittext_book_item_Author);
        EditText editTextTranslator=findViewById(R.id.edittext_book_item_Translator);
        EditText editTextPublisher=findViewById(R.id.edittext_book_item_Publisher);
        EditText editTextPubDate=findViewById(R.id.edittext_book_item_PubDate);
        EditText editTextISBN=findViewById(R.id.edittext_book_item_ISBN);
        Spinner editTextReadingState=findViewById(R.id.edittext_book_item_ReadingState);
        Spinner editTextBookShelf=findViewById(R.id.edittext_book_item_BookShelf);
        EditText editTextNotes=findViewById(R.id.edittext_book_item_Notes);
        TextView editTextLabel=findViewById(R.id.edittext_book_item_Label);
        EditText editTextWebsite=findViewById(R.id.edittext_book_item_Website);
        switch (item.getItemId()) {
            case R.id.action_save://监听菜单按钮
                Intent intent=new Intent();
                Bundle bundle=new Bundle();
//                bundle.putInt("id",editIntid.getId());
                bundle.putInt("id",id);
                bundle.putString("title",editTextTitle.getText().toString());
//                double price=Double.parseDouble(editTextPrice.getText().toString());
                bundle.putString("Author",editTextAuthor.getText().toString());
                bundle.putString("Translator",editTextTranslator.getText().toString());
                bundle.putString("Publisher",editTextPublisher.getText().toString());
                bundle.putString("PubDate",editTextPubDate.getText().toString());
                bundle.putString("ISBN",editTextISBN.getText().toString());
                bundle.putInt("ReadingState",editTextReadingState.getSelectedItemPosition());
                bundle.putInt("BookShelf",editTextBookShelf.getSelectedItemPosition());
                bundle.putString("Notes",editTextNotes.getText().toString());
                bundle.putString("Label",editTextLabel.getText().toString());
                bundle.putString("Website",editTextWebsite.getText().toString());
                bundle.putString("UUID",uuid);
//                bundle.putDouble("price",price);

//                if(book==null){
//                    book=new Book(editTextTitle.getText().toString(),id,editTextAuthor.getText().toString(),editTextTranslator.getText().toString(),
//                            editTextPublisher.getText().toString(),editTextPubDate.getText().toString(),editTextISBN.getText().toString(),editTextReadingState.getSelectedItemPosition()
//                    ,editTextBookShelf.getSelectedItemPosition(),editTextNotes.getText().toString(),editTextLabel.getText().toString(),
//                            editTextWebsite.getText().toString(),BookListMainActivity.bookBookShelfHashMap.get(name).size());
//                }else{
//                    book.setId(id);
//                    book.setTitle(editTextTitle.getText().toString());
//                    book.setAuthor(editTextAuthor.getText().toString());
//                    book.setTranslator(editTextTranslator.getText().toString());
//                    book.setPublisher(editTextPublisher.getText().toString());
//                    book.setPubDate(editTextPubDate.getText().toString());
//                    book.setISBN(editTextISBN.getText().toString());
//                    book.setReadingState(editTextReadingState.getSelectedItemPosition());
//                    book.setBookShelf(editTextBookShelf.getSelectedItemPosition());
//                    book.setNotes(editTextNotes.getText().toString());
//                    book.setLabel(editTextLabel.getText().toString());
//                    book.setWebsite(editTextWebsite.getText().toString());
//                }


                bundle.putInt("position",position);
                bundle.putSerializable("Book",book);

                intent.putExtras(bundle);

                new DataSaver().save(InputBookItemActivity.this,BookListMainActivity.bookList,BookListMainActivity.bookShelfStringArray);

                setResult(RESULT_CODE_SUCCESS,intent);
                InputBookItemActivity.this.finish();
                break;
            case R.id.action_changecover:
                id=random.nextInt(11);
                Drawable drawable=getBaseContext().getResources().getDrawable(mArray[id]);
                ImageView cover=findViewById(R.id.book_image);
                cover.setImageDrawable(drawable);

//                cover.setImageURI(Uri.parse("mnt/sdcard/leotech/pic/wel_logo.png"));
                break;
        }
        return super.onOptionsItemSelected(item);
    }

//    private void setReadingStatus() {
//        Spinner readingStatusSpinner = (Spinner) findViewById(R.id.reading_status_spinner);
//        ArrayAdapter<CharSequence> readingStatusArrayAdapter = ArrayAdapter.createFromResource(
//                this, R.array.reading_status_array, R.layout.spinner_item);
//        readingStatusArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//        readingStatusSpinner.setAdapter(readingStatusArrayAdapter);
//        readingStatusSpinner.setSelection(mBook.getReadingStatus());
//        readingStatusSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//                mBook.setReadingStatus(i);
////                Log.i(TAG, "Click and set Reading status " + i);
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> adapterView) {
//
//            }
//        });
//    }
}